/*
 * Created on 2004-7-28
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
package com.wsj.common.security;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author Administrator
 *
 * To change the template for this generated type comment go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
public class MyEncrypt {
	
	/**
	 * �Ƿ�Ҫ���м���
	 */
	private static final boolean isEncrypt=true; 
	
	
	public static String encrypt16Md5(String plainText )
	{ 
		try { 
		MessageDigest md = MessageDigest.getInstance("MD5"); 
		md.update(plainText.getBytes()); 
		byte b[] = md.digest(); 
		int i; 
		StringBuffer buf = new StringBuffer(""); 
		for (int offset = 0; offset < b.length; offset++) { 
		i = b[offset]; 
		if(i<0) i+= 256; 
		if(i<16) 
		buf.append("0"); 
		buf.append(Integer.toHexString(i)); 
		} 
		
		//System.out.println("result: " + buf.toString());//32位的加密 
		
		return buf.toString().substring(8,24);//16位的加密 
		} catch (NoSuchAlgorithmException e) { 
//		 TODO Auto-generated catch block 
		e.printStackTrace(); 
		}
		
		return "";
   }  
	
	
	public static void main(String[] arg)
	{
		MyEncrypt m = new MyEncrypt();
		String ret =m.encrypt16Md5("123456");
		System.out.println("16 位密文:"+ret);
		
		
	}

	
	
	/**
	 * �����msg���ܣ����ܽ��Ϊ32λ�ַ�
	 * @param key ��Կ
	 * @param msg ����
	 * @return ���ܽ��
	 */
	public static String encryptMD5(String key, String msg) {

		String key2 = key.toLowerCase();
		if(!isEncrypt) return msg;
		
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(key2.getBytes());
			md.update(msg.getBytes());
			return toHex2(md.digest());

		} catch (Exception e) {
			e.printStackTrace();
		}
		return msg;
	}

	/**
	 * ��bufferת��λ16λ�ַ�����buffer�е�ÿ��byte)չλ16λ��ASCII
	 * @param buffer
	 * @return
	 */
	private static String toHex2(byte buffer[]) {

		StringBuffer sb = new StringBuffer();
		String s = null;
		for (int i = 0; i < buffer.length; i++) {
			s = Integer.toHexString((int) buffer[i] & 0xff);
			if (s.length() < 2) {
				sb.append('0');
			}
			sb.append(s);
		}
		return sb.toString();
	}
}
